package com.example.demo.bese;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.demo.task.ChooserBase;
import com.example.library.base.MBaseActivity;
import com.orhanobut.logger.Logger;

import java.lang.reflect.Constructor;
import java.util.Collection;
import java.util.Map;
import java.util.TreeMap;

public class BaseActivity extends MBaseActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initPermission();
    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onPause() {
        super.onPause();

    }

    @Override
    protected void onStop() {
        super.onStop();

    }

    @Override
    protected void onRestart() {
        super.onRestart();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    private void initPermission() {
        // 获取文件处理权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
                PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    100);
        }
    }

    private Map<String, ChooserBase> mActivityChooserTaskCache = new TreeMap<>();
    /**
     * 获取chooser
     *
     * @param clazz
     * @return
     */
    public <H extends ChooserBase> H getChooserTask(Class clazz) {
        try {
            ChooserBase chooserBase = mActivityChooserTaskCache.get(clazz.getName());
            if (chooserBase == null) {
                Constructor constructor = clazz.getConstructor(BaseActivity.class);
                chooserBase = (ChooserBase)constructor.newInstance(this);
                mActivityChooserTaskCache.put(clazz.getName(), chooserBase);
            }
            return (H)chooserBase;
        } catch (Exception e) {
            Logger.e(e, e.getMessage());
        }
        return null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Collection<ChooserBase> chooserTasks = mActivityChooserTaskCache.values();
        for (ChooserBase chooserBase : chooserTasks) {
            chooserBase.onActivityResult(requestCode, resultCode, data);
        }
    }
}
